/*
 * cubeLinkedList.c
 *
 *
 */

#include <stdbool.h>
#include <stdlib.h>
#include "cubeLinkedList.h"

char del(LinkedList *ll)
{
    //Get the node at the head, and update where faces are being drawn from in
    //  the node
    char ret;
    ret = ll->head->faces[ll->head->start_pos++];

    //See if the array is empty (start == where a new node would go)
    if (ll->head->start_pos == ll->head->nxt_pos)
    {
        //Save the head pointer for deallocation
        LLNode *old = ll->head;

        //Update the head to the previous item in the linked list
        ll->head = ll->head->prev;

        //Deallocate the previous head node
        free(old);
    }
    return ret;
}

void add(LinkedList *ll, char face)
{
    // check if setting up brand new linked list, or end node is full
    if (isLLEmpty(ll) || (ll->tail->nxt_pos > 40))
    {
        // start new linked list
        LLNode *new;
        new = malloc(sizeof(LLNode));

        new->start_pos = 0;
        new->nxt_pos = 0;

        new->prev = NULL;

        if (isLLEmpty(ll))
        {
            //Set head to new node
            ll->head = new;
        }
        else
        {
            //Appending new node to tail
            ll->tail->prev = new;
        }
        //Update last node to new
        ll->tail = new;
    }

    //Put face in next open position, set turns for that face = 1, and update next
    ll->tail->faces[ll->tail->nxt_pos] = face;
    ll->tail->turns[ll->tail->nxt_pos++] = 1;
}

void initLinkedList(LinkedList *ll)
{
    ll->head = NULL;
    ll->tail = NULL;
}

bool isLLEmpty(LinkedList * const ll)
{
    return ll->head == NULL;
}

void reduce(LinkedList *ll)
{
    //TODO Set this up so it iterates through the linked list once it contains
    //  a completed path
    //  Probably should output the resulting path with putchar or printf
    int last = ll->tail->nxt_pos - 1;
    int seclast = ll->tail->nxt_pos - 2;
    int thirdlast = ll->tail->nxt_pos - 3;

    if ((ll->tail->faces[thirdlast] == ll->tail->faces[seclast])
            && (ll->tail->faces[seclast] == ll->tail->faces[last]))
    {
        del(ll);
        del(ll);
        ll->tail->turns[thirdlast] = 3;
    }
    else if (ll->tail->faces[seclast] == ll->tail->faces[last])
    {
        del(ll);
        ll->tail->turns[seclast] = 2;
    }
}

